package org.wmq.javafxmapcollectionstandalone.mapper.impl;

import com.alibaba.fastjson.JSON;
import org.wmq.javafxmapcollectionstandalone.mapper.MapEntityMapper;
import org.wmq.javafxmapcollectionstandalone.model.Entity.MapEntity;

import java.io.*;

public class MapEntityMapperImplByFileSystem implements MapEntityMapper {
    public static final String FILE_PREFIX = "D:\\map_collection_data\\map_data\\";
    @Override
    public MapEntity selectById(Long id) {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return null;
        }
        try (FileInputStream fileInputStream = new FileInputStream(file)){
            String jsonString = new String(fileInputStream.readAllBytes());
            MapEntity result = JSON.parseObject(jsonString, MapEntity.class);
            result.setId(id);
            return result;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void insert(MapEntity mapEntity) {
        String filename = FILE_PREFIX + mapEntity.getId() + ".txt";
        File file = new File(filename);
        if (file.exists()){
            return;
        }
        try(FileOutputStream fileOutputStream = new FileOutputStream(file)){
            fileOutputStream.write(JSON.toJSONString(mapEntity).getBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(MapEntity mapEntity) {
        String filename = FILE_PREFIX + mapEntity.getId() + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return;
        }
        try(FileOutputStream fileOutputStream = new FileOutputStream(file)){
            fileOutputStream.write(JSON.toJSONString(mapEntity).getBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        String filename = FILE_PREFIX + id + ".txt";
        File file = new File(filename);
        if (!file.exists()){
            return;
        }
        file.delete();
    }
}
